//
//  ReaderAlbumsViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/8/23.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

private let headerIdentifier = "PersonAlbumsHeaderView"
private let cellIdentifier = "PersonAlbumCell"

struct SimplePerson {
  enum PersonType {
    case unknown, reader, writer
  }
  
  var type: PersonType = .unknown
  var name: String
  var identifier: Int
}

class PersonAlbumsViewController: BaseViewController {
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var collectionView: UICollectionView!
  
  // MARK: - Private vars
  
  private var isFirstLoaded = true
  private var resultItems: [SearchResultItem]?
  private var selectedAlbumIdentifier = -1
  
  // MARK: - Private methods
  
  private func loadData() {
    if let person = simplePerson {
      var urlString: String? = nil
      switch person.type {
      case .reader:
        urlString = APIURLStrings.getReaderAlbums(readerIdentifier: person.identifier)
        title = "主播节目"
      case .writer:
        urlString = APIURLStrings.getWriterAlbums(writerIdentifier: person.identifier)
        title = "作者节目"
      default:
        break
      }
      
      if let url = urlString {
        API.shared.requestAPI (
          url,
          method: .get,
          header: API.shared.memeberHeader,
          successCallback: { json in
            if let resultArray = json["albums"].array, resultArray.count > 0 {
              self.resultItems = resultArray.map {
                SearchResultItem (
                  id: $0["id"].intValue,
                  albumName: $0["album_name"].stringValue,
                  type: SearchResultItem.AlbumType(rawValue: $0["type"].stringValue)!,
                  coverImageURL: URL(string: "\(APIURLStrings.imagePrefix)/\($0["cover"])")!
                )
              }
              self.collectionView.reloadData()
            } else {
              self.resultItems = nil
              self.collectionView.reloadData()
            }
            
            UIView.animate(withDuration: 0.3) {
              self.collectionView.alpha = 1
            }
        }) { (message, code) in
          loggingPrint("[\(code)]: \(message)")
        }
      }
    }
  }
  
  // MARK: - Public vars
  
  var simplePerson: SimplePerson?
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    collectionView.alpha = 0
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    if isFirstLoaded {
      loadData()
    }
  }
  
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    if isFirstLoaded {
      isFirstLoaded = false
    }
  }
  
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if selectedAlbumIdentifier >= 0 && segue.identifier == "ShowAlbumDetailFromPerson" {
      let albumDetailViewController = segue.destination as! AlbumDetailViewController
      albumDetailViewController.albumIdentifier = selectedAlbumIdentifier
    }
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
}

// MARK: - UICollectionViewDataSource

extension PersonAlbumsViewController: UICollectionViewDataSource {
  
  func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
  }
  
  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return resultItems?.count ?? 0
  }
  
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! PersonAlbumCell
    
    if let item = resultItems?[indexPath.row] {
      let isVipAlbum = (item.type == .vip)
      cell.prepare (
        coverImageURL: item.coverImageURL,
        contentName: item.albumName,
        isVipAlbum: isVipAlbum
      )
    }
    return cell
  }
  
  func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    if kind == UICollectionView.elementKindSectionHeader {
      let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier, for: indexPath) as! PersonAlbumsHeaderView
      header.tipLabel.text = "\(simplePerson?.name ?? "神秘人")的节目"
      return header
    } else {
      return UICollectionReusableView()
    }
  }
}

// MARK: - UICollectionViewDelegate

extension PersonAlbumsViewController: UICollectionViewDelegate {
  
  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if let album = resultItems?[indexPath.row] {
      selectedAlbumIdentifier = album.id
      performSegue(withIdentifier: "ShowAlbumDetailFromPerson", sender: self)
      collectionView.deselectItem(at: indexPath, animated: true)
    }
  }
}

extension PersonAlbumsViewController: UICollectionViewDelegateFlowLayout {
  
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = (collectionView.width - 32) / 2 - 8
    let height = width * 196 / 143 - 30
    return CGSize(width: width, height: height)
  }
  
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize (
      width: collectionView.width,
      height: PersonAlbumsHeaderView.defaultHeight
    )
  }
}
